<template>
  <el-dialog
    v-model="dialogVisible"
    title="高级搜索"
    width="700px"
    :before-close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="searchForm"
      label-width="120px"
      class="advanced-search-form"
    >
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="敏感词内容">
            <el-input
              v-model="searchForm.word"
              placeholder="支持模糊搜索"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="敏感词类型">
            <el-select
              v-model="searchForm.type"
              placeholder="选择类型"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="type in sensitiveWordTypes"
                :key="type.value"
                :label="type.label"
                :value="type.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="严重程度">
            <el-select
              v-model="searchForm.severity"
              placeholder="选择严重程度"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="severity in severityLevels"
                :key="severity.value"
                :label="severity.label"
                :value="severity.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="过滤模式">
            <el-select
              v-model="searchForm.filterMode"
              placeholder="选择过滤模式"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="mode in filterModes"
                :key="mode.value"
                :label="mode.label"
                :value="mode.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="状态">
            <el-select
              v-model="searchForm.status"
              placeholder="选择状态"
              clearable
              style="width: 100%"
            >
              <el-option label="启用" :value="1" />
              <el-option label="禁用" :value="0" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="标签">
            <el-input
              v-model="searchForm.tags"
              placeholder="搜索标签内容"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 100%"
              @change="handleDateRangeChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="匹配次数">
            <div class="match-count-range">
              <el-input-number
                v-model="matchCountRange.min"
                :min="0"
                placeholder="最小值"
                controls-position="right"
                style="width: 45%"
              />
              <span class="range-separator">至</span>
              <el-input-number
                v-model="matchCountRange.max"
                :min="0"
                placeholder="最大值"
                controls-position="right"
                style="width: 45%"
              />
            </div>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="排序字段">
            <el-select
              v-model="searchForm.sortField"
              placeholder="选择排序字段"
              style="width: 100%"
            >
              <el-option label="创建时间" value="createTime" />
              <el-option label="更新时间" value="updateTime" />
              <el-option label="敏感词内容" value="word" />
              <el-option label="匹配次数" value="matchCount" />
              <el-option label="严重程度" value="severity" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="排序方向">
            <el-radio-group v-model="searchForm.sortOrder">
              <el-radio :value="'desc'">降序</el-radio>
              <el-radio :value="'asc'">升序</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 快速筛选 -->
      <el-divider content-position="left">快速筛选</el-divider>

      <div class="quick-filters">
        <el-button-group>
          <el-button size="small" @click="applyQuickFilter('today')">
            今日新增
          </el-button>
          <el-button size="small" @click="applyQuickFilter('week')">
            本周新增
          </el-button>
          <el-button size="small" @click="applyQuickFilter('month')">
            本月新增
          </el-button>
        </el-button-group>

        <el-button-group style="margin-left: 16px">
          <el-button size="small" @click="applyQuickFilter('high-severity')">
            高严重程度
          </el-button>
          <el-button size="small" @click="applyQuickFilter('active')">
            活跃敏感词
          </el-button>
          <el-button size="small" @click="applyQuickFilter('disabled')">
            已禁用
          </el-button>
        </el-button-group>
      </div>

      <!-- 搜索条件预览 -->
      <el-divider content-position="left">搜索条件预览</el-divider>

      <div class="search-preview">
        <el-tag
          v-for="condition in searchConditions"
          :key="condition.key"
          :type="condition.type"
          size="small"
          closable
          class="condition-tag"
          @close="removeCondition(condition.key)"
        >
          {{ condition.label }}: {{ condition.value }}
        </el-tag>
        <el-text v-if="searchConditions.length === 0" type="info">
          暂无搜索条件
        </el-text>
      </div>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleReset">重置</el-button>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from "vue";
import {
  SensitiveWordType,
  SeverityLevel,
  FilterMode,
  type SensitiveWordQuery
} from "@/api/sensitive-word-management";

interface Props {
  /** 对话框可见性 */
  visible: boolean;
  /** 搜索表单数据 */
  searchForm: SensitiveWordQuery;
}

const props = defineProps<Props>();

const emit = defineEmits<{
  "update:visible": [visible: boolean];
  search: [params: SensitiveWordQuery];
}>();

// 响应式数据
const formRef = ref();
const dateRange = ref<[string, string] | null>(null);
const matchCountRange = reactive({
  min: undefined as number | undefined,
  max: undefined as number | undefined
});

// 搜索表单（本地副本）
const searchForm = reactive<SensitiveWordQuery>({ ...props.searchForm });

// 计算属性
const dialogVisible = computed({
  get: () => props.visible,
  set: value => emit("update:visible", value)
});

// 选项数据
const sensitiveWordTypes = [
  { label: "脏话", value: SensitiveWordType.PROFANITY },
  { label: "政治敏感", value: SensitiveWordType.POLITICS },
  { label: "广告", value: SensitiveWordType.ADVERTISEMENT },
  { label: "暴力内容", value: SensitiveWordType.VIOLENCE },
  { label: "违法内容", value: SensitiveWordType.ILLEGAL },
  { label: "垃圾信息", value: SensitiveWordType.SPAM }
];

const severityLevels = [
  { label: "轻微", value: SeverityLevel.LIGHT },
  { label: "一般", value: SeverityLevel.NORMAL },
  { label: "中等", value: SeverityLevel.MEDIUM },
  { label: "严重", value: SeverityLevel.SERIOUS },
  { label: "极严重", value: SeverityLevel.CRITICAL }
];

const filterModes = [
  { label: "替换模式", value: FilterMode.REPLACE },
  { label: "拦截模式", value: FilterMode.BLOCK }
];

// 搜索条件预览
const searchConditions = computed(() => {
  const conditions: Array<{
    key: string;
    label: string;
    value: string;
    type: string;
  }> = [];

  if (searchForm.word) {
    conditions.push({
      key: "word",
      label: "敏感词",
      value: searchForm.word,
      type: "primary"
    });
  }

  if (searchForm.type) {
    const typeLabel =
      sensitiveWordTypes.find(t => t.value === searchForm.type)?.label || "";
    conditions.push({
      key: "type",
      label: "类型",
      value: typeLabel,
      type: "success"
    });
  }

  if (searchForm.severity) {
    const severityLabel =
      severityLevels.find(s => s.value === searchForm.severity)?.label || "";
    conditions.push({
      key: "severity",
      label: "严重程度",
      value: severityLabel,
      type: "warning"
    });
  }

  if (searchForm.filterMode) {
    const modeLabel =
      filterModes.find(m => m.value === searchForm.filterMode)?.label || "";
    conditions.push({
      key: "filterMode",
      label: "过滤模式",
      value: modeLabel,
      type: "info"
    });
  }

  if (searchForm.status !== undefined) {
    conditions.push({
      key: "status",
      label: "状态",
      value: searchForm.status === 1 ? "启用" : "禁用",
      type: searchForm.status === 1 ? "success" : "danger"
    });
  }

  if (searchForm.tags) {
    conditions.push({
      key: "tags",
      label: "标签",
      value: searchForm.tags,
      type: "primary"
    });
  }

  if (searchForm.startTime && searchForm.endTime) {
    conditions.push({
      key: "dateRange",
      label: "创建时间",
      value: `${searchForm.startTime} 至 ${searchForm.endTime}`,
      type: "info"
    });
  }

  return conditions;
});

// 日期范围变化
const handleDateRangeChange = (dates: [string, string] | null) => {
  if (dates) {
    searchForm.startTime = dates[0];
    searchForm.endTime = dates[1];
  } else {
    searchForm.startTime = "";
    searchForm.endTime = "";
  }
};

// 快速筛选
const applyQuickFilter = (type: string) => {
  const now = new Date();
  const today = now.toISOString().slice(0, 10);

  switch (type) {
    case "today":
      searchForm.startTime = today;
      searchForm.endTime = today;
      dateRange.value = [today, today];
      break;
    case "week":
      const weekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
      const weekAgoStr = weekAgo.toISOString().slice(0, 10);
      searchForm.startTime = weekAgoStr;
      searchForm.endTime = today;
      dateRange.value = [weekAgoStr, today];
      break;
    case "month":
      const monthAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
      const monthAgoStr = monthAgo.toISOString().slice(0, 10);
      searchForm.startTime = monthAgoStr;
      searchForm.endTime = today;
      dateRange.value = [monthAgoStr, today];
      break;
    case "high-severity":
      searchForm.severity = SeverityLevel.SERIOUS;
      break;
    case "active":
      matchCountRange.min = 1;
      break;
    case "disabled":
      searchForm.status = 0;
      break;
  }
};

// 移除搜索条件
const removeCondition = (key: string) => {
  switch (key) {
    case "word":
      searchForm.word = "";
      break;
    case "type":
      searchForm.type = undefined;
      break;
    case "severity":
      searchForm.severity = undefined;
      break;
    case "filterMode":
      searchForm.filterMode = undefined;
      break;
    case "status":
      searchForm.status = undefined;
      break;
    case "tags":
      searchForm.tags = "";
      break;
    case "dateRange":
      searchForm.startTime = "";
      searchForm.endTime = "";
      dateRange.value = null;
      break;
  }
};

// 重置表单
const handleReset = () => {
  Object.assign(searchForm, {
    word: "",
    type: undefined,
    severity: undefined,
    filterMode: undefined,
    status: undefined,
    tags: "",
    startTime: "",
    endTime: "",
    sortField: "createTime",
    sortOrder: "desc"
  });
  dateRange.value = null;
  matchCountRange.min = undefined;
  matchCountRange.max = undefined;
};

// 搜索
const handleSearch = () => {
  emit("search", { ...searchForm });
};

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false;
};

// 监听props变化
watch(
  () => props.searchForm,
  newForm => {
    Object.assign(searchForm, newForm);
    if (newForm.startTime && newForm.endTime) {
      dateRange.value = [newForm.startTime, newForm.endTime];
    }
  },
  { deep: true, immediate: true }
);
</script>

<style scoped>
/* 深色模式适配 */
@media (prefers-color-scheme: dark) {
  .search-preview {
    background: #374151;
    border-color: #4b5563;
  }
}

.advanced-search-form {
  max-height: 60vh;
  overflow-y: auto;
}

.match-count-range {
  display: flex;
  align-items: center;
  width: 100%;
}

.range-separator {
  margin: 0 8px;
  color: #666;
}

.quick-filters {
  margin: 16px 0;
}

.search-preview {
  min-height: 40px;
  padding: 12px;
  background: #f8f9fa;
  border: 1px dashed #d9d9d9;
  border-radius: 8px;
}

.condition-tag {
  margin: 4px 8px 4px 0;
}

.dialog-footer {
  text-align: center;
}
</style>
